<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/9/13
 * Time: 00:32
 */
namespace thans\log\controller;

class Log
{
    protected static $instance;

    protected static $title = '';

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return \think\Request
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    public static function setTitle($title)
    {
        self::$title = $title;
    }
    public static function add($title = '')
    {
        $data['action'] = request()->module() . '/' . request()->controller() . '/' . request()->action();
        $data['title']  = self::$title ?: '';
        if ($data['title'] == '') {
            $uri = $data['action'];
            $url = request()->get() ? $uri . '?' . http_build_query(request()->get()) : $uri;

            $res           = db('auth_rule')->where('name', $url)->field('title')->find();
            $data['title'] = $res['title'];
        }
        $param               = request()->get();
        $data['param']       = $param ? http_build_query($param, '', '&') : '';
        $login_info          = cmf_is_login();
        $data['uid']         = $login_info['code'] == '1001' ? $login_info['data']['uid'] : 0;
        $data['url']         = request()->url();
        $data['add_time']    = app()->getBeginTime();
        $data['data']        = json_encode(request()->post());
        $data['device_type'] = cmf_get_device_type();
        $data['user_agent']  = request()->server('HTTP_USER_AGENT');
        $data['ip']          = request()->ip();
        $data['country']     = '未知';
        $data['region']      = '未知';
        $data['city']        = '未知';
        //TODO:ip进行分析
        $data['use_time'] = microtime(true) - request()->server('REQUEST_TIME_FLOAT');
        db('action')->insert($data);
    }

}
